<!DOCTYPE html>
<html lang="en">
<head>
  <title>Writing TCP servers and clients - Vert.x</title>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Vert.x is a tool-kit for building reactive applications on the JVM." name="description">
  <link href="http://vertx.io/stylesheets/docs.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/stylesheets/font-awesome.min.css" media="screen" rel="stylesheet">
  <link href="http://vertx.io/javascripts/styles/rainbow.min.css" media="screen" rel="stylesheet">
  <!-- IE 6-8 support of HTML 5 elements -->
  <!--[if lt IE 9]>
  <script src="http://static.jboss.org/theme/js/libs/html5/pre3.6/html5.min.js"></script>
  <![endif]-->

  <link rel="apple-touch-icon" sizes="57x57" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="http://vertx.io/assets/favicons/vertx-favicon-7/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="http://vertx.io/assets/favicons/vertx-favicon-7/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="http://vertx.io/assets/favicons/vertx-favicon-7/manifest.json">
  <link rel="mask-icon" href="http://vertx.io/assets/favicons/vertx-favicon-7/safari-pinned-tab.svg" color="#5bbad5">
  <meta name="msapplication-TileColor" content="#7d3194">
  <meta name="msapplication-TileImage" content="http://vertx.io/assets/favicons/vertx-favicon-7/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link href="http://fonts.googleapis.com/css?family=Ubuntu:400,500,700,400italic" rel="stylesheet" type="text/css">
  <link rel="alternate" type="application/rss+xml" title="RSS"
     href="http://vertx.io/feed.xml">
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-30144458-1', 'auto');
    ga('create', 'UA-71153120-1', 'auto', 'tracker');
    ga('send', 'pageview');
    ga('tracker.send', 'pageview');
  </script>
</head>
<body>

<a href="http://www.reactivemanifesto.org/" id="reactive-manifesto-banner">
  <img style="border: 0; position: fixed; right: 0; top:0; z-index: 9000"
    src="http://d379ifj7s9wntv.cloudfront.net/reactivemanifesto/images/ribbons/we-are-reactive-black-right.png">
</a>

<a id="skippy" class="sr-only sr-only-focusable" href="#content"><div class="container"><span class="skiplink-text">Skip to main content</span></div></a>

<header class="navbar navbar-default navbar-static-top" id="top" role="banner">
  <div class="container">
    <div class="navbar-header">
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#vertx-navbar-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a href="http://vertx.io/" class="navbar-brand"><img alt="Brand" src="http://vertx.io/assets/logo-sm.png"></a>
    </div>
    <nav class="collapse navbar-collapse" id="vertx-navbar-collapse">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="http://vertx.io/download/">Download</a></li>
        <li><a href="http://vertx.io/docs/">Documentation</a></li>
        <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
        <li><a href="http://vertx.io/community/">Community</a></li>
        <li><a href="http://vertx.io/materials/">Materials</a></li>
        <li><a href="http://vertx.io/blog/">Blog</a></li>        
      </ul>
    </nav>
  </div>
</header>



  <div class="page-header" id="content">
    <div class="container">
      <div class="row">
        <div class="col-sm-12">
          <h1>Writing TCP servers and clients</h1>
          
        </div>
      </div>
    </div>
  </div>




<div id="content">
  <div class="container docs-content">
    <div class="row">
      <div class="col-sm-12 col-md-push-9 col-md-3 hidden-xs hidden-sm">
        <div id="sidebar" data-spy="affix">
          <ul class="sectlevel1">
<li><a href="#_writing_tcp_servers_and_clients">Writing TCP servers and clients</a>
<ul class="sectlevel2">
<li><a href="#_creating_a_tcp_server">Creating a TCP server</a></li>
<li><a href="#_configuring_a_tcp_server">Configuring a TCP server</a></li>
<li><a href="#_start_the_server_listening">Start the Server Listening</a></li>
<li><a href="#_listening_on_a_random_port">Listening on a random port</a></li>
<li><a href="#_getting_notified_of_incoming_connections">Getting notified of incoming connections</a></li>
<li><a href="#_reading_data_from_the_socket">Reading data from the socket</a></li>
<li><a href="#_writing_data_to_a_socket">Writing data to a socket</a></li>
<li><a href="#_closed_handler">Closed handler</a></li>
<li><a href="#_handling_exceptions">Handling exceptions</a></li>
<li><a href="#_event_bus_write_handler">Event bus write handler</a></li>
<li><a href="#_local_and_remote_addresses">Local and remote addresses</a></li>
<li><a href="#_sending_files_or_resources_from_the_classpath">Sending files or resources from the classpath</a></li>
<li><a href="#_streaming_sockets">Streaming sockets</a></li>
<li><a href="#_upgrading_connections_to_ssl_tls">Upgrading connections to SSL/TLS</a></li>
<li><a href="#_closing_a_tcp_server">Closing a TCP Server</a></li>
<li><a href="#_automatic_clean_up_in_verticles">Automatic clean-up in verticles</a></li>
<li><a href="#_scaling_sharing_tcp_servers">Scaling - sharing TCP servers</a></li>
<li><a href="#_creating_a_tcp_client">Creating a TCP client</a></li>
<li><a href="#_configuring_a_tcp_client">Configuring a TCP client</a></li>
<li><a href="#_making_connections">Making connections</a></li>
<li><a href="#_configuring_connection_attempts">Configuring connection attempts</a></li>
<li><a href="#logging_network_activity">Logging network activity</a></li>
<li><a href="#ssl">Configuring servers and clients to work with SSL/TLS</a></li>
<li><a href="#_using_a_proxy_for_client_connections">Using a proxy for client connections</a></li>
</ul>
</li>
</ul>
        </div>
      </div>
      <div class="col-sm-12 col-md-pull-3 col-md-9">
        <div class="toc hidden-md hidden-lg">
          <h2>Table of Contents</h2>
          <ul class="sectlevel1">
<li><a href="#_writing_tcp_servers_and_clients">Writing TCP servers and clients</a>
<ul class="sectlevel2">
<li><a href="#_creating_a_tcp_server">Creating a TCP server</a></li>
<li><a href="#_configuring_a_tcp_server">Configuring a TCP server</a></li>
<li><a href="#_start_the_server_listening">Start the Server Listening</a></li>
<li><a href="#_listening_on_a_random_port">Listening on a random port</a></li>
<li><a href="#_getting_notified_of_incoming_connections">Getting notified of incoming connections</a></li>
<li><a href="#_reading_data_from_the_socket">Reading data from the socket</a></li>
<li><a href="#_writing_data_to_a_socket">Writing data to a socket</a></li>
<li><a href="#_closed_handler">Closed handler</a></li>
<li><a href="#_handling_exceptions">Handling exceptions</a></li>
<li><a href="#_event_bus_write_handler">Event bus write handler</a></li>
<li><a href="#_local_and_remote_addresses">Local and remote addresses</a></li>
<li><a href="#_sending_files_or_resources_from_the_classpath">Sending files or resources from the classpath</a></li>
<li><a href="#_streaming_sockets">Streaming sockets</a></li>
<li><a href="#_upgrading_connections_to_ssl_tls">Upgrading connections to SSL/TLS</a></li>
<li><a href="#_closing_a_tcp_server">Closing a TCP Server</a></li>
<li><a href="#_automatic_clean_up_in_verticles">Automatic clean-up in verticles</a></li>
<li><a href="#_scaling_sharing_tcp_servers">Scaling - sharing TCP servers</a></li>
<li><a href="#_creating_a_tcp_client">Creating a TCP client</a></li>
<li><a href="#_configuring_a_tcp_client">Configuring a TCP client</a></li>
<li><a href="#_making_connections">Making connections</a></li>
<li><a href="#_configuring_connection_attempts">Configuring connection attempts</a></li>
<li><a href="#logging_network_activity">Logging network activity</a></li>
<li><a href="#ssl">Configuring servers and clients to work with SSL/TLS</a></li>
<li><a href="#_using_a_proxy_for_client_connections">Using a proxy for client connections</a></li>
</ul>
</li>
</ul>
        </div>
        <div class="sect1">
<h2 id="_writing_tcp_servers_and_clients">Writing TCP servers and clients</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Vert.x allows you to easily write non blocking TCP clients and servers.</p>
</div>
<div class="sect2">
<h3 id="_creating_a_tcp_server">Creating a TCP server</h3>
<div class="paragraph">
<p>The simplest way to create a TCP server, using all default options is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_configuring_a_tcp_server">Configuring a TCP server</h3>
<div class="paragraph">
<p>If you don&#8217;t want the default, a server can be configured by passing in a <code><a href="../../apidocs/io/vertx/core/net/NetServerOptions.html">NetServerOptions</a></code>
instance when creating it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().setPort(4321);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_start_the_server_listening">Start the Server Listening</h3>
<div class="paragraph">
<p>To tell the server to listen for incoming requests you use one of the <code><a href="../../apidocs/io/vertx/core/net/NetServer.html#listen--">listen</a></code>
alternatives.</p>
</div>
<div class="paragraph">
<p>To tell the server to listen at the host and port as specified in the options:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();
server.listen();</code></pre>
</div>
</div>
<div class="paragraph">
<p>Or to specify the host and port in the call to listen, ignoring what is configured in the options:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();
server.listen(1234, "localhost");</code></pre>
</div>
</div>
<div class="paragraph">
<p>The default host is <code>0.0.0.0</code> which means 'listen on all available addresses' and the default port is <code>0</code>, which is a
special value that instructs the server to find a random unused local port and use that.</p>
</div>
<div class="paragraph">
<p>The actual bind is asynchronous so the server might not actually be listening until some time <strong>after</strong> the call to
listen has returned.</p>
</div>
<div class="paragraph">
<p>If you want to be notified when the server is actually listening you can provide a handler to the <code>listen</code> call.
For example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();
server.listen(1234, "localhost", res -&gt; {
  if (res.succeeded()) {
    System.out.println("Server is now listening!");
  } else {
    System.out.println("Failed to bind!");
  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_listening_on_a_random_port">Listening on a random port</h3>
<div class="paragraph">
<p>If <code>0</code> is used as the listening port, the server will find an unused random port to listen on.</p>
</div>
<div class="paragraph">
<p>To find out the real port the server is listening on you can call <code><a href="../../apidocs/io/vertx/core/net/NetServer.html#actualPort--">actualPort</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();
server.listen(0, "localhost", res -&gt; {
  if (res.succeeded()) {
    System.out.println("Server is now listening on actual port: " + server.actualPort());
  } else {
    System.out.println("Failed to bind!");
  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_getting_notified_of_incoming_connections">Getting notified of incoming connections</h3>
<div class="paragraph">
<p>To be notified when a connection is made you need to set a <code><a href="../../apidocs/io/vertx/core/net/NetServer.html#connectHandler-io.vertx.core.Handler-">connectHandler</a></code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();
server.connectHandler(socket -&gt; {
  // Handle the connection in here
});</code></pre>
</div>
</div>
<div class="paragraph">
<p>When a connection is made the handler will be called with an instance of <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html">NetSocket</a></code>.</p>
</div>
<div class="paragraph">
<p>This is a socket-like interface to the actual connection, and allows you to read and write data as well as do various
other things like close the socket.</p>
</div>
</div>
<div class="sect2">
<h3 id="_reading_data_from_the_socket">Reading data from the socket</h3>
<div class="paragraph">
<p>To read data from the socket you set the <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#handler-io.vertx.core.Handler-">handler</a></code> on the
socket.</p>
</div>
<div class="paragraph">
<p>This handler will be called with an instance of <code><a href="../../apidocs/io/vertx/core/buffer/Buffer.html">Buffer</a></code> every time data is received on
the socket.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServer server = vertx.createNetServer();
server.connectHandler(socket -&gt; {
  socket.handler(buffer -&gt; {
    System.out.println("I received some bytes: " + buffer.length());
  });
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_writing_data_to_a_socket">Writing data to a socket</h3>
<div class="paragraph">
<p>You write to a socket using one of <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#write-io.vertx.core.buffer.Buffer-">write</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer buffer = Buffer.buffer().appendFloat(12.34f).appendInt(123);
socket.write(buffer);

// Write a string in UTF-8 encoding
socket.write("some data");

// Write a string using the specified encoding
socket.write("some data", "UTF-16");</code></pre>
</div>
</div>
<div class="paragraph">
<p>Write operations are asynchronous and may not occur until some time after the call to write has returned.</p>
</div>
</div>
<div class="sect2">
<h3 id="_closed_handler">Closed handler</h3>
<div class="paragraph">
<p>If you want to be notified when a socket is closed, you can set a <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#closeHandler-io.vertx.core.Handler-">closeHandler</a></code>
on it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">socket.closeHandler(v -&gt; {
  System.out.println("The socket has been closed");
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_handling_exceptions">Handling exceptions</h3>
<div class="paragraph">
<p>You can set an <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#exceptionHandler-io.vertx.core.Handler-">exceptionHandler</a></code> to receive any
exceptions that happen on the socket.</p>
</div>
</div>
<div class="sect2">
<h3 id="_event_bus_write_handler">Event bus write handler</h3>
<div class="paragraph">
<p>Every socket automatically registers a handler on the event bus, and when any buffers are received in this handler,
it writes them to itself.</p>
</div>
<div class="paragraph">
<p>This enables you to write data to a socket which is potentially in a completely different verticle or even in a
different Vert.x instance by sending the buffer to the address of that handler.</p>
</div>
<div class="paragraph">
<p>The address of the handler is given by <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#writeHandlerID--">writeHandlerID</a></code></p>
</div>
</div>
<div class="sect2">
<h3 id="_local_and_remote_addresses">Local and remote addresses</h3>
<div class="paragraph">
<p>The local address of a <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html">NetSocket</a></code> can be retrieved using <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#localAddress--">localAddress</a></code>.</p>
</div>
<div class="paragraph">
<p>The remote address, (i.e. the address of the other end of the connection) of a <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html">NetSocket</a></code>
can be retrieved using <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#remoteAddress--">remoteAddress</a></code>.</p>
</div>
</div>
<div class="sect2">
<h3 id="_sending_files_or_resources_from_the_classpath">Sending files or resources from the classpath</h3>
<div class="paragraph">
<p>Files and classpath resources can be written to the socket directly using <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#sendFile-java.lang.String-">sendFile</a></code>. This can be a very
efficient way to send files, as it can be handled by the OS kernel directly where supported by the operating system.</p>
</div>
<div class="paragraph">
<p>Please see the chapter about <a href="#classpath">serving files from the classpath</a> for restrictions of the
classpath resolution or disabling it.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">socket.sendFile("myfile.dat");</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_streaming_sockets">Streaming sockets</h3>
<div class="paragraph">
<p>Instances of <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html">NetSocket</a></code> are also <code><a href="../../apidocs/io/vertx/core/streams/ReadStream.html">ReadStream</a></code> and
<code><a href="../../apidocs/io/vertx/core/streams/WriteStream.html">WriteStream</a></code> instances so they can be used to pump data to or from other
read and write streams.</p>
</div>
<div class="paragraph">
<p>See the chapter on <a href="#streams">streams and pumps</a> for more information.</p>
</div>
</div>
<div class="sect2">
<h3 id="_upgrading_connections_to_ssl_tls">Upgrading connections to SSL/TLS</h3>
<div class="paragraph">
<p>A non SSL/TLS connection can be upgraded to SSL/TLS using <code><a href="../../apidocs/io/vertx/core/net/NetSocket.html#upgradeToSsl-io.vertx.core.Handler-">upgradeToSsl</a></code>.</p>
</div>
<div class="paragraph">
<p>The server or client must be configured for SSL/TLS for this to work correctly. Please see the <a href="#ssl">chapter on SSL/TLS</a>
for more information.</p>
</div>
</div>
<div class="sect2">
<h3 id="_closing_a_tcp_server">Closing a TCP Server</h3>
<div class="paragraph">
<p>Call <code><a href="../../apidocs/io/vertx/core/net/NetServer.html#close--">close</a></code> to close the server. Closing the server closes any open connections
and releases all server resources.</p>
</div>
<div class="paragraph">
<p>The close is actually asynchronous and might not complete until some time after the call has returned.
If you want to be notified when the actual close has completed then you can pass in a handler.</p>
</div>
<div class="paragraph">
<p>This handler will then be called when the close has fully completed.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">server.close(res -&gt; {
  if (res.succeeded()) {
    System.out.println("Server is now closed");
  } else {
    System.out.println("close failed");
  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_automatic_clean_up_in_verticles">Automatic clean-up in verticles</h3>
<div class="paragraph">
<p>If you&#8217;re creating TCP servers and clients from inside verticles, those servers and clients will be automatically closed
when the verticle is undeployed.</p>
</div>
</div>
<div class="sect2">
<h3 id="_scaling_sharing_tcp_servers">Scaling - sharing TCP servers</h3>
<div class="paragraph">
<p>The handlers of any TCP server are always executed on the same event loop thread.</p>
</div>
<div class="paragraph">
<p>This means that if you are running on a server with a lot of cores, and you only have this one instance
deployed then you will have at most one core utilised on your server.</p>
</div>
<div class="paragraph">
<p>In order to utilise more cores of your server you will need to deploy more instances of the server.</p>
</div>
<div class="paragraph">
<p>You can instantiate more instances programmatically in your code:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">for (int i = 0; i &lt; 10; i++) {
  NetServer server = vertx.createNetServer();
  server.connectHandler(socket -&gt; {
    socket.handler(buffer -&gt; {
      // Just echo back the data
      socket.write(buffer);
    });
  });
  server.listen(1234, "localhost");
}</code></pre>
</div>
</div>
<div class="paragraph">
<p>or, if you are using verticles you can simply deploy more instances of your server verticle by using the <code>-instances</code> option
on the command line:</p>
</div>
<div class="literalblock">
<div class="content">
<pre>vertx run com.mycompany.MyVerticle -instances 10</pre>
</div>
</div>
<div class="paragraph">
<p>or when programmatically deploying your verticle</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">DeploymentOptions options = new DeploymentOptions().setInstances(10);
vertx.deployVerticle("com.mycompany.MyVerticle", options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Once you do this you will find the echo server works functionally identically to before, but all your cores on your
server can be utilised and more work can be handled.</p>
</div>
<div class="paragraph">
<p>At this point you might be asking yourself <strong>'How can you have more than one server listening on the
same host and port? Surely you will get port conflicts as soon as you try and deploy more than one instance?'</strong></p>
</div>
<div class="paragraph">
<p><em>Vert.x does a little magic here.*</em></p>
</div>
<div class="paragraph">
<p>When you deploy another server on the same host and port as an existing server it doesn&#8217;t actually try and create a
new server listening on the same host/port.</p>
</div>
<div class="paragraph">
<p>Instead it internally maintains just a single server, and, as incoming connections arrive it distributes
them in a round-robin fashion to any of the connect handlers.</p>
</div>
<div class="paragraph">
<p>Consequently Vert.x TCP servers can scale over available cores while each instance remains single threaded.</p>
</div>
</div>
<div class="sect2">
<h3 id="_creating_a_tcp_client">Creating a TCP client</h3>
<div class="paragraph">
<p>The simplest way to create a TCP client, using all default options is as follows:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClient client = vertx.createNetClient();</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_configuring_a_tcp_client">Configuring a TCP client</h3>
<div class="paragraph">
<p>If you don&#8217;t want the default, a client can be configured by passing in a <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html">NetClientOptions</a></code>
instance when creating it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().setConnectTimeout(10000);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_making_connections">Making connections</h3>
<div class="paragraph">
<p>To make a connection to a server you use <code><a href="../../apidocs/io/vertx/core/net/NetClient.html#connect-int-java.lang.String-io.vertx.core.Handler-">connect</a></code>,
specifying the port and host of the server and a handler that will be called with a result containing the
<code><a href="../../apidocs/io/vertx/core/net/NetSocket.html">NetSocket</a></code> when connection is successful or with a failure if connection failed.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().setConnectTimeout(10000);
NetClient client = vertx.createNetClient(options);
client.connect(4321, "localhost", res -&gt; {
  if (res.succeeded()) {
    System.out.println("Connected!");
    NetSocket socket = res.result();
  } else {
    System.out.println("Failed to connect: " + res.cause().getMessage());
  }
});</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_configuring_connection_attempts">Configuring connection attempts</h3>
<div class="paragraph">
<p>A client can be configured to automatically retry connecting to the server in the event that it cannot connect.
This is configured with <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html#setReconnectInterval-long-">setReconnectInterval</a></code> and
<code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html#setReconnectAttempts-int-">setReconnectAttempts</a></code>.</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<div class="title">Note</div>
</td>
<td class="content">
Currently Vert.x will not attempt to reconnect if a connection fails, reconnect attempts and interval
only apply to creating initial connections.
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
    setReconnectAttempts(10).
    setReconnectInterval(500);

NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>By default, multiple connection attempts are disabled.</p>
</div>
</div>
<div class="sect2">
<h3 id="logging_network_activity">Logging network activity</h3>
<div class="paragraph">
<p>For debugging purposes, network activity can be logged:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().setLogActivity(true);

NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>for the client</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().setLogActivity(true);

NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Network activity is logged by Netty with the <code>DEBUG</code> level and with the <code>io.netty.handler.logging.LoggingHandler</code>
name. When using network activity logging there are a few things to keep in mind:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>logging is not performed by Vert.x logging but by Netty</p>
</li>
<li>
<p>this is <strong>not</strong> a production feature</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Netty will try to locate the following logger implementations, in the following order:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Slf4j</p>
</li>
<li>
<p>Log4j</p>
</li>
<li>
<p>JDK</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The presense of the slf4j or log4j classes on the classpath is enough to pick up the logging implementation.</p>
</div>
<div class="paragraph">
<p>The logger implementation can be forced to a specific implementation by setting Netty&#8217;s internal logger implementation directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">// Force logging to SLF4J
InternalLoggerFactory.setDefaultFactory(Log4JLoggerFactory.INSTANCE);</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="ssl">Configuring servers and clients to work with SSL/TLS</h3>
<div class="paragraph">
<p>TCP clients and servers can be configured to use <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">Transport Layer Security</a>
- earlier versions of TLS were known as SSL.</p>
</div>
<div class="paragraph">
<p>The APIs of the servers and clients are identical whether or not SSL/TLS is used, and it&#8217;s enabled by configuring
the <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html">NetClientOptions</a></code> or <code><a href="../../apidocs/io/vertx/core/net/NetServerOptions.html">NetServerOptions</a></code> instances used
to create the servers or clients.</p>
</div>
<div class="sect3">
<h4 id="_enabling_ssl_tls_on_the_server">Enabling SSL/TLS on the server</h4>
<div class="paragraph">
<p>SSL/TLS is enabled with  <code><a href="../../apidocs/io/vertx/core/net/NetServerOptions.html#setSsl-boolean-">ssl</a></code>.</p>
</div>
<div class="paragraph">
<p>By default it is disabled.</p>
</div>
</div>
<div class="sect3">
<h4 id="_specifying_key_certificate_for_the_server">Specifying key/certificate for the server</h4>
<div class="paragraph">
<p>SSL/TLS servers usually provide certificates to clients in order verify their identity to clients.</p>
</div>
<div class="paragraph">
<p>Certificates/keys can be configured for servers in several ways:</p>
</div>
<div class="paragraph">
<p>The first method is by specifying the location of a Java key-store which contains the certificate and private key.</p>
</div>
<div class="paragraph">
<p>Java key stores can be managed with the <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html">keytool</a>
utility which ships with the JDK.</p>
</div>
<div class="paragraph">
<p>The password for the key store should also be provided:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().setSsl(true).setKeyStoreOptions(
    new JksOptions().
        setPath("/path/to/your/server-keystore.jks").
        setPassword("password-of-your-keystore")
);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively you can read the key store yourself as a buffer and provide that directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myKeyStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-keystore.jks");
JksOptions jksOptions = new JksOptions().
    setValue(myKeyStoreAsABuffer).
    setPassword("password-of-your-keystore");
NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setKeyStoreOptions(jksOptions);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Key/certificate in PKCS#12 format (<a href="http://en.wikipedia.org/wiki/PKCS_12" class="bare">http://en.wikipedia.org/wiki/PKCS_12</a>), usually with the <code>.pfx</code>  or the <code>.p12</code>
extension can also be loaded in a similar fashion than JKS key stores:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().setSsl(true).setPfxKeyCertOptions(
    new PfxOptions().
        setPath("/path/to/your/server-keystore.pfx").
        setPassword("password-of-your-keystore")
);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myKeyStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-keystore.pfx");
PfxOptions pfxOptions = new PfxOptions().
    setValue(myKeyStoreAsABuffer).
    setPassword("password-of-your-keystore");
NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setPfxKeyCertOptions(pfxOptions);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Another way of providing server private key and certificate separately using <code>.pem</code> files.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().setSsl(true).setPemKeyCertOptions(
    new PemKeyCertOptions().
        setKeyPath("/path/to/your/server-key.pem").
        setCertPath("/path/to/your/server-cert.pem")
);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myKeyAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-key.pem");
Buffer myCertAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-cert.pem");
PemKeyCertOptions pemOptions = new PemKeyCertOptions().
    setKeyValue(myKeyAsABuffer).
    setCertValue(myCertAsABuffer);
NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setPemKeyCertOptions(pemOptions);
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Keep in mind that pem configuration, the private key is not crypted.</p>
</div>
</div>
<div class="sect3">
<h4 id="_specifying_trust_for_the_server">Specifying trust for the server</h4>
<div class="paragraph">
<p>SSL/TLS servers can use a certificate authority in order to verify the identity of the clients.</p>
</div>
<div class="paragraph">
<p>Certificate authorities can be configured for servers in several ways:</p>
</div>
<div class="paragraph">
<p>Java trust stores can be managed with the <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html">keytool</a>
utility which ships with the JDK.</p>
</div>
<div class="paragraph">
<p>The password for the trust store should also be provided:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setClientAuth(ClientAuth.REQUIRED).
    setTrustStoreOptions(
        new JksOptions().
            setPath("/path/to/your/truststore.jks").
            setPassword("password-of-your-truststore")
    );
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Alternatively you can read the trust store yourself as a buffer and provide that directly:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myTrustStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/truststore.jks");
NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setClientAuth(ClientAuth.REQUIRED).
    setTrustStoreOptions(
        new JksOptions().
            setValue(myTrustStoreAsABuffer).
            setPassword("password-of-your-truststore")
    );
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Certificate authority in PKCS#12 format (<a href="http://en.wikipedia.org/wiki/PKCS_12" class="bare">http://en.wikipedia.org/wiki/PKCS_12</a>), usually with the <code>.pfx</code>  or the <code>.p12</code>
extension can also be loaded in a similar fashion than JKS trust stores:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setClientAuth(ClientAuth.REQUIRED).
    setPfxTrustOptions(
        new PfxOptions().
            setPath("/path/to/your/truststore.pfx").
            setPassword("password-of-your-truststore")
    );
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myTrustStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/truststore.pfx");
NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setClientAuth(ClientAuth.REQUIRED).
    setPfxTrustOptions(
        new PfxOptions().
            setValue(myTrustStoreAsABuffer).
            setPassword("password-of-your-truststore")
    );
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Another way of providing server certificate authority using a list <code>.pem</code> files.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setClientAuth(ClientAuth.REQUIRED).
    setPemTrustOptions(
        new PemTrustOptions().
            addCertPath("/path/to/your/server-ca.pem")
    );
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myCaAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/server-ca.pfx");
NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setClientAuth(ClientAuth.REQUIRED).
    setPemTrustOptions(
        new PemTrustOptions().
            addCertValue(myCaAsABuffer)
    );
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_enabling_ssl_tls_on_the_client">Enabling SSL/TLS on the client</h4>
<div class="paragraph">
<p>Net Clients can also be easily configured to use SSL. They have the exact same API when using SSL as when using standard sockets.</p>
</div>
<div class="paragraph">
<p>To enable SSL on a NetClient the function setSSL(true) is called.</p>
</div>
</div>
<div class="sect3">
<h4 id="_client_trust_configuration">Client trust configuration</h4>
<div class="paragraph">
<p>If the <code><a href="../../apidocs/io/vertx/core/net/ClientOptionsBase.html#setTrustAll-boolean-">trustALl</a></code> is set to true on the client, then the client will
trust all server certificates. The connection will still be encrypted but this mode is vulnerable to 'man in the middle' attacks. I.e. you can&#8217;t
be sure who you are connecting to. Use this with caution. Default value is false.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setTrustAll(true);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>If <code><a href="../../apidocs/io/vertx/core/net/ClientOptionsBase.html#setTrustAll-boolean-">trustAll</a></code> is not set then a client trust store must be
configured and should contain the certificates of the servers that the client trusts.</p>
</div>
<div class="paragraph">
<p>By default, host verification is disabled on the client.
To enable host verification, set the algorithm to use on your client (only HTTPS and LDAPS is currently supported):</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
        setSsl(true).
        setHostnameVerificationAlgorithm("HTTPS");
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Likewise server configuration, the client trust can be configured in several ways:</p>
</div>
<div class="paragraph">
<p>The first method is by specifying the location of a Java trust-store which contains the certificate authority.</p>
</div>
<div class="paragraph">
<p>It is just a standard Java key store, the same as the key stores on the server side. The client
trust store location is set by using the function <code><a href="../../apidocs/io/vertx/core/net/JksOptions.html#setPath-java.lang.String-">path</a></code> on the
<code><a href="../../apidocs/io/vertx/core/net/JksOptions.html">jks options</a></code>. If a server presents a certificate during connection which is not
in the client trust store, the connection attempt will not succeed.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setTrustStoreOptions(
        new JksOptions().
            setPath("/path/to/your/truststore.jks").
            setPassword("password-of-your-truststore")
    );
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myTrustStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/truststore.jks");
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setTrustStoreOptions(
        new JksOptions().
            setValue(myTrustStoreAsABuffer).
            setPassword("password-of-your-truststore")
    );
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Certificate authority in PKCS#12 format (<a href="http://en.wikipedia.org/wiki/PKCS_12" class="bare">http://en.wikipedia.org/wiki/PKCS_12</a>), usually with the <code>.pfx</code>  or the <code>.p12</code>
extension can also be loaded in a similar fashion than JKS trust stores:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setPfxTrustOptions(
        new PfxOptions().
            setPath("/path/to/your/truststore.pfx").
            setPassword("password-of-your-truststore")
    );
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myTrustStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/truststore.pfx");
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setPfxTrustOptions(
        new PfxOptions().
            setValue(myTrustStoreAsABuffer).
            setPassword("password-of-your-truststore")
    );
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Another way of providing server certificate authority using a list <code>.pem</code> files.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setPemTrustOptions(
        new PemTrustOptions().
            addCertPath("/path/to/your/ca-cert.pem")
    );
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myTrustStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/ca-cert.pem");
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setPemTrustOptions(
        new PemTrustOptions().
            addCertValue(myTrustStoreAsABuffer)
    );
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_specifying_key_certificate_for_the_client">Specifying key/certificate for the client</h4>
<div class="paragraph">
<p>If the server requires client authentication then the client must present its own certificate to the server when
connecting. The client can be configured in several ways:</p>
</div>
<div class="paragraph">
<p>The first method is by specifying the location of a Java key-store which contains the key and certificate.
Again it&#8217;s just a regular Java key store. The client keystore location is set by using the function
<code><a href="../../apidocs/io/vertx/core/net/JksOptions.html#setPath-java.lang.String-">path</a></code> on the
<code><a href="../../apidocs/io/vertx/core/net/JksOptions.html">jks options</a></code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().setSsl(true).setKeyStoreOptions(
    new JksOptions().
        setPath("/path/to/your/client-keystore.jks").
        setPassword("password-of-your-keystore")
);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myKeyStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/client-keystore.jks");
JksOptions jksOptions = new JksOptions().
    setValue(myKeyStoreAsABuffer).
    setPassword("password-of-your-keystore");
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setKeyStoreOptions(jksOptions);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Key/certificate in PKCS#12 format (<a href="http://en.wikipedia.org/wiki/PKCS_12" class="bare">http://en.wikipedia.org/wiki/PKCS_12</a>), usually with the <code>.pfx</code>  or the <code>.p12</code>
extension can also be loaded in a similar fashion than JKS key stores:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().setSsl(true).setPfxKeyCertOptions(
    new PfxOptions().
        setPath("/path/to/your/client-keystore.pfx").
        setPassword("password-of-your-keystore")
);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myKeyStoreAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/client-keystore.pfx");
PfxOptions pfxOptions = new PfxOptions().
    setValue(myKeyStoreAsABuffer).
    setPassword("password-of-your-keystore");
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setPfxKeyCertOptions(pfxOptions);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Another way of providing server private key and certificate separately using <code>.pem</code> files.</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().setSsl(true).setPemKeyCertOptions(
    new PemKeyCertOptions().
        setKeyPath("/path/to/your/client-key.pem").
        setCertPath("/path/to/your/client-cert.pem")
);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myKeyAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/client-key.pem");
Buffer myCertAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/client-cert.pem");
PemKeyCertOptions pemOptions = new PemKeyCertOptions().
    setKeyValue(myKeyAsABuffer).
    setCertValue(myCertAsABuffer);
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setPemKeyCertOptions(pemOptions);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Keep in mind that pem configuration, the private key is not crypted.</p>
</div>
</div>
<div class="sect3">
<h4 id="_revoking_certificate_authorities">Revoking certificate authorities</h4>
<div class="paragraph">
<p>Trust can be configured to use a certificate revocation list (CRL) for revoked certificates that should no
longer be trusted. The <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html#addCrlPath-java.lang.String-">crlPath</a></code> configures
the crl list to use:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setTrustStoreOptions(trustOptions).
    addCrlPath("/path/to/your/crl.pem");
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Buffer configuration is also supported:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">Buffer myCrlAsABuffer = vertx.fileSystem().readFileBlocking("/path/to/your/crl.pem");
NetClientOptions options = new NetClientOptions().
    setSsl(true).
    setTrustStoreOptions(trustOptions).
    addCrlValue(myCrlAsABuffer);
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_configuring_the_cipher_suite">Configuring the Cipher suite</h4>
<div class="paragraph">
<p>By default, the TLS configuration will use the Cipher suite of the JVM running Vert.x. This Cipher suite can be
configured with a suite of enabled ciphers:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setKeyStoreOptions(keyStoreOptions).
    addEnabledCipherSuite("ECDHE-RSA-AES128-GCM-SHA256").
    addEnabledCipherSuite("ECDHE-ECDSA-AES128-GCM-SHA256").
    addEnabledCipherSuite("ECDHE-RSA-AES256-GCM-SHA384").
    addEnabledCipherSuite("CDHE-ECDSA-AES256-GCM-SHA384");
NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Cipher suite can be specified on the <code><a href="../../apidocs/io/vertx/core/net/NetServerOptions.html">NetServerOptions</a></code> or <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html">NetClientOptions</a></code> configuration.</p>
</div>
</div>
<div class="sect3">
<h4 id="_configuring_tls_protocol_versions">Configuring TLS protocol versions</h4>
<div class="paragraph">
<p>By default, the TLS configuration will use the following protocol versions: SSLv2Hello, TLSv1, TLSv1.1 and TLSv1.2. Protocol versions can be
configured by explicitly adding enabled protocols:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setKeyStoreOptions(keyStoreOptions).
    addEnabledSecureTransportProtocol("TLSv1.1").
    addEnabledSecureTransportProtocol("TLSv1.2");
    NetServer server = vertx.createNetServer(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>Protocol versions can be specified on the <code><a href="../../apidocs/io/vertx/core/net/NetServerOptions.html">NetServerOptions</a></code> or <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html">NetClientOptions</a></code> configuration.</p>
</div>
</div>
<div class="sect3">
<h4 id="_ssl_engine">SSL engine</h4>
<div class="paragraph">
<p>The engine implementation can be configured to use <a href="https://www.openssl.org">OpenSSL</a> instead of the JDK implementation.
OpenSSL provides better performances and CPU usage than the JDK engine, as well as JDK version independence.</p>
</div>
<div class="paragraph">
<p>The engine options to use is</p>
</div>
<div class="ulist">
<ul>
<li>
<p>the <code><a href="../../apidocs/io/vertx/core/net/TCPSSLOptions.html#getSslEngineOptions--">getSslEngineOptions</a></code> options when it is set</p>
</li>
<li>
<p>otherwise <code><a href="../../apidocs/io/vertx/core/net/JdkSSLEngineOptions.html">JdkSSLEngineOptions</a></code></p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetServerOptions options = new NetServerOptions().
    setSsl(true).
    setKeyStoreOptions(keyStoreOptions);

// Use JDK SSL engine explicitly
options = new NetServerOptions().
    setSsl(true).
    setKeyStoreOptions(keyStoreOptions).
    setJdkSslEngineOptions(new JdkSSLEngineOptions());

// Use OpenSSL engine
options = new NetServerOptions().
    setSsl(true).
    setKeyStoreOptions(keyStoreOptions).
    setOpenSslEngineOptions(new OpenSSLEngineOptions());</code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_application_layer_protocol_negotiation">Application-Layer Protocol Negotiation</h4>
<div class="paragraph">
<p>ALPN is a TLS extension for applicationl layer protocol negotitation. It is used by HTTP/2: during the TLS handshake
the client gives the list of application protocols it accepts and the server responds with a protocol it supports.</p>
</div>
<div class="paragraph">
<p>Java 8 does not supports ALPN out of the box, so ALPN should be enabled by other means:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><em>OpenSSL</em> support</p>
</li>
<li>
<p><em>Jetty-ALPN</em> support</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>The engine options to use is</p>
</div>
<div class="ulist">
<ul>
<li>
<p>the <code><a href="../../apidocs/io/vertx/core/net/TCPSSLOptions.html#getSslEngineOptions--">getSslEngineOptions</a></code> options when it is set</p>
</li>
<li>
<p><code><a href="../../apidocs/io/vertx/core/net/JdkSSLEngineOptions.html">JdkSSLEngineOptions</a></code> when ALPN is available for JDK</p>
</li>
<li>
<p><code><a href="../../apidocs/io/vertx/core/net/OpenSSLEngineOptions.html">OpenSSLEngineOptions</a></code> when ALPN is available for OpenSSL</p>
</li>
<li>
<p>otherwise it fails</p>
</li>
</ul>
</div>
<div class="sect4">
<h5 id="_openssl_alpn_support">OpenSSL ALPN support</h5>
<div class="paragraph">
<p>OpenSSL provides native ALPN support.</p>
</div>
<div class="paragraph">
<p>OpenSSL requires to configure <code><a href="../../apidocs/io/vertx/core/net/TCPSSLOptions.html#setOpenSslEngineOptions-io.vertx.core.net.OpenSSLEngineOptions-">setOpenSslEngineOptions</a></code>
and use <a href="http://netty.io/wiki/forked-tomcat-native.html">netty-tcnative</a> jar on the classpath. Using tcnative may require
OpenSSL to be installed on your OS depending on the tcnative implementation.</p>
</div>
</div>
<div class="sect4">
<h5 id="_jetty_alpn_support">Jetty-ALPN support</h5>
<div class="paragraph">
<p>Jetty-ALPN is a small jar that overrides a few classes of Java 8 distribution to support ALPN.</p>
</div>
<div class="paragraph">
<p>The JVM must be started with the <em>alpn-boot-${version}.jar</em> in its <code>bootclasspath</code>:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>-Xbootclasspath/p:/path/to/alpn-boot${version}.jar</pre>
</div>
</div>
<div class="paragraph">
<p>where ${version} depends on the JVM version, e.g. <em>8.1.7.v20160121</em> for <em>OpenJDK 1.8.0u74</em> . The complete
list is available on the <a href="http://www.eclipse.org/jetty/documentation/current/alpn-chapter.html">Jetty-ALPN page</a>.</p>
</div>
<div class="paragraph">
<p>The main drawback is that the version depends on the JVM.</p>
</div>
<div class="paragraph">
<p>To solve this problem the <em><a href="https://github.com/jetty-project/jetty-alpn-agent">Jetty ALPN agent</a></em> can be use instead. The agent is a JVM agent that will chose the correct
ALPN version for the JVM running it:</p>
</div>
<div class="listingblock">
<div class="content">
<pre>-javaagent:/path/to/alpn/agent</pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_using_a_proxy_for_client_connections">Using a proxy for client connections</h3>
<div class="paragraph">
<p>The <code><a href="../../apidocs/io/vertx/core/net/NetClient.html">NetClient</a></code> supports either a HTTP/1.x <em>CONNECT</em>, <em>SOCKS4a</em> or <em>SOCKS5</em> proxy.</p>
</div>
<div class="paragraph">
<p>The proxy can be configured in the <code><a href="../../apidocs/io/vertx/core/net/NetClientOptions.html">NetClientOptions</a></code> by setting a
<code><a href="../../apidocs/io/vertx/core/net/ProxyOptions.html">ProxyOptions</a></code> object containing proxy type, hostname, port and optionally username and password.</p>
</div>
<div class="paragraph">
<p>Here&#8217;s an example:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="prettyprint highlight"><code class="language-java" data-lang="java">NetClientOptions options = new NetClientOptions()
    .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5)
        .setHost("localhost").setPort(1080)
        .setUsername("username").setPassword("secret"));
NetClient client = vertx.createNetClient(options);</code></pre>
</div>
</div>
<div class="paragraph">
<p>The DNS resolution is always done on the proxy server, to achieve the functionality of a SOCKS4 client, it is necessary
to resolve the DNS address locally.</p>
</div>
</div>
</div>
</div>

        

        
          <div id="footer">
            <div id="footer-text">
              
                Last updated 2016-09-12 08:38:04 CEST
              
              
            </div>
          </div>
        
      </div>
    </div>
  </div>
</div>

<footer>
  <div class="container">
    <div class="row">
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Vert.x</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/">Home</a></li>
          <li><a href="http://vertx.io/download/">Download</a></li>
          <li><a href="http://vertx.io/docs/">Documentation</a></li>
          <li><a href="https://github.com/vert-x3/wiki/wiki">Wiki</a></li>
          <li><a href="http://vertx.io/blog/">Blog</a></li>
          <li><a href="http://vertx.io/vertx2/" class="vertx-2-link">Vert.x 2</a></li>
        </ul>
      </div>
      <div class="col-xs-6 col-sm-3 col-md-3 col-lg-2">
        <h2>Community</h2>
        <ul class="list-unstyled">
          <li><a href="http://vertx.io/community/">Help &amp; Contributors</a></li>
          <li><a href="http://vertx.io/materials/">Learning materials</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx">User Group</a></li>
          <li><a href="https://groups.google.com/forum/?fromgroups#!forum/vertx-dev">Developer Group</a></li>
        </ul>
      </div>

      <div class="col-xs-12 col-sm-6 col-lg-offset-2 col-md-6 copyright">
        <p>Vert.x is open source and dual licensed under the <a href="https://www.eclipse.org/org/documents/epl-v10.php">Eclipse Public License 1.0</a> and <a href="https://www.apache.org/licenses/LICENSE-2.0.html">Apache License 2.0</a>.</p>
        <p>This website is licensed under the <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC BY-SA 3.0 License</a>.<br>
        Design by <a href="http://www.michel-kraemer.com">Michel Kr&auml;mer</a>. <a href="http://www.entypo.com">Entypo pictograms</a> by Daniel Bruce.</p>
        <div class="row">
          <div class="col-xs-12 col-lg-offset-1 col-md-5">
            <a href="http://eclipse.org">
            <img class="logo eclipse-logo" src="http://vertx.io/assets/eclipse_logo_grey_small.png" width="204" height="48">
            </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-0 col-md-5">
            <a href="http://cloudbees.com">
            <img class="logo cloudbees-logo" src="http://vertx.io/assets/Button-Built-on-CB-1-grey.png" width="180" height="48">
           </a>
          </div>
          <div class="col-xs-12 col-md-offset-2 col-lg-offset-1 col-md-5 jprofiler">
            <a href="http://www.ej-technologies.com/products/jprofiler/overview.html"
            style="text-decoration:none">
            <img class="logo jprofiler-logo" src="http://vertx.io/assets/jprofiler-logo.png" width="48" height="48"><span class="jprofiler-logo">&nbsp; JPROFILER</span>
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</footer>

<script src="http://static.jboss.org/theme/js/libs/jquery/jquery-1.9.1.min.js"></script>
<script src="http://vertx.io/javascripts/bootstrap.min.js"></script>
<script src="http://vertx.io/javascripts/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>



<script src="http://vertx.io/javascripts/sidebar.js"></script>


</body>
</html>
